package com.uxhao.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uxhao.eduservice.entity.EduCourse;
import com.uxhao.eduservice.entity.EduCourseDescription;
import com.uxhao.eduservice.entity.adminVo.DayDataVo;
import com.uxhao.eduservice.entity.adminVo.WeekDataVo;
import com.uxhao.eduservice.entity.frontvo.CourseFrontInfoVo;
import com.uxhao.eduservice.entity.frontvo.CourseFrontQuery;
import com.uxhao.eduservice.entity.query.CourseQuery;
import com.uxhao.eduservice.entity.vo.CourseInfoVo;
import com.uxhao.eduservice.entity.vo.CoursePublishVo;
import com.uxhao.eduservice.mapper.EduCourseMapper;
import com.uxhao.eduservice.service.EduChapterService;
import com.uxhao.eduservice.service.EduCourseDescriptionService;
import com.uxhao.eduservice.service.EduCourseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.uxhao.eduservice.service.EduVideoService;
import com.uxhao.servicebase.exceptionhandler.QLLException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author uxhao
 * @since 2022/01/11
 */
@Service
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse> implements EduCourseService {

    //课程描述
    @Autowired
    private EduCourseDescriptionService eduCourseDescriptionService;

    @Autowired
    private EduVideoService eduVideoService;

    @Autowired
    private EduChapterService eduChapterService;

    //添加课程基本信息的方法
    //返回添加实体的id
    @Override
    public String saveCourseInfo(CourseInfoVo courseInfoVo) {
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVo, eduCourse);//复制属性
        boolean save = this.save(eduCourse);

        if (!save) throw new QLLException(20001, "添加课程信息失败");

        //课程描述
        EduCourseDescription eduCourseDescription = new EduCourseDescription();
        eduCourseDescription.setId(eduCourse.getId());
        eduCourseDescription.setDescription(courseInfoVo.getDescription());
        boolean save1 = eduCourseDescriptionService.save(eduCourseDescription);
        if (!save1) throw new QLLException(20001, "添加课程描述失败");

        return eduCourse.getId();
    }

    @Override
    public CourseInfoVo getCourseInfoById(String courseId) {

        //1 查询课程表
        EduCourse eduCourse = this.getById(courseId);
        if (eduCourse == null) throw new QLLException(20001, "数据不存在");
        CourseInfoVo courseInfoVo = new CourseInfoVo();
        BeanUtils.copyProperties(eduCourse, courseInfoVo);

        //2 查询描述表
        EduCourseDescription description = eduCourseDescriptionService.getById(courseId);
        if (description != null) courseInfoVo.setDescription(description.getDescription());

        return courseInfoVo;
    }

    @Override
    public void updateCourseInfoById(CourseInfoVo courseInfoVo) {
        //保存课程基本信息
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVo, eduCourse);
        boolean resultCourse = this.updateById(eduCourse);
        if (!resultCourse) throw new QLLException(20001, "课程信息保存失败");

        //保存课程详情信息
        EduCourseDescription courseDescription = new EduCourseDescription();
        courseDescription.setDescription(courseInfoVo.getDescription());
        courseDescription.setId(eduCourse.getId());
        boolean resultDescription = eduCourseDescriptionService.saveOrUpdate(courseDescription);
        if (!resultDescription) throw new QLLException(20001, "课程详情信息保存失败");


    }

    @Override
    public CoursePublishVo getCoursePublishVoById(String id) {
        CoursePublishVo coursePublishVo = baseMapper.selectCoursePublishVoById(id);
        return coursePublishVo;
    }

    //课程发布
    @Override
    public boolean publishCourseById(String id) {
        EduCourse course = new EduCourse();
        course.setId(id);
        course.setIsDeleted(0);
        course.setStatus(EduCourse.COURSE_NORMAL);
        Integer count = baseMapper.updateById(course);
        return null != count && count > 0;
    }

    //分页带查询条件
    @Override
    public void pageQuery(Page<EduCourse> pageParam, CourseQuery courseQuery) {
        QueryWrapper<EduCourse> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("gmt_create");

        //如果条件为空 返回全部
        if (courseQuery == null) {
            baseMapper.selectPage(pageParam, queryWrapper);
            return;
        }

        String title = courseQuery.getTitle();
        String teacherId = courseQuery.getTeacherId();
        String subjectParentId = courseQuery.getSubjectParentId();
        String subjectId = courseQuery.getSubjectId();

        if (!StringUtils.isEmpty(title)) queryWrapper.like("title", title);

        if (!StringUtils.isEmpty(teacherId)) queryWrapper.eq("teacher_id", teacherId);

        if (!StringUtils.isEmpty(subjectParentId)) queryWrapper.eq("subject_parent_id", subjectParentId);

        if (!StringUtils.isEmpty(subjectId)) queryWrapper.eq("subject_id", subjectId);

        baseMapper.selectPage(pageParam, queryWrapper);
    }

    //删除课程 同时通过课程id删除章节 小节 描述
    @Override
    @Transactional
    public boolean removeCourseById(String courseId) {
        //1.根据课程id删除小节
        eduVideoService.removeVideoByCourseId(courseId);

        //2.根据课程id删除章节
        eduChapterService.removeChapterByCourseId(courseId);

        //3.根据课程id删除描述
        eduCourseDescriptionService.removeById(courseId);

        Integer result = baseMapper.deleteById(courseId);
        return null != result && result > 0;
    }

    @Override
    public List<EduCourse> selectByTeacherId(String teacherId) {

        QueryWrapper<EduCourse> queryWrapper = new QueryWrapper();

        queryWrapper.eq("teacher_id", teacherId);
        //按照最后更新时间倒序排列
        queryWrapper.orderByDesc("gmt_modified");

        List<EduCourse> courses = baseMapper.selectList(queryWrapper);
        return courses;
    }

    @Override
    public Map<String, Object> getCourseFrontList(Page<EduCourse> pageParam, CourseFrontQuery courseQuery) {
        QueryWrapper<EduCourse> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(courseQuery.getSubjectParentId())) {
            queryWrapper.eq("subject_parent_id", courseQuery.getSubjectParentId());
        }

        if (!StringUtils.isEmpty(courseQuery.getSubjectId())) {
            queryWrapper.eq("subject_id", courseQuery.getSubjectId());
        }

        if (!StringUtils.isEmpty(courseQuery.getBuyCountSort())) {
            queryWrapper.orderByDesc("buy_count");
        }

        if (!StringUtils.isEmpty(courseQuery.getGmtCreateSort())) {
            queryWrapper.orderByDesc("gmt_create");
        }

        if (!StringUtils.isEmpty(courseQuery.getPriceSort())) {
            queryWrapper.orderByDesc("price");
        }

        baseMapper.selectPage(pageParam, queryWrapper);

        List<EduCourse> records = pageParam.getRecords();
        long current = pageParam.getCurrent();
        long pages = pageParam.getPages();
        long size = pageParam.getSize();
        long total = pageParam.getTotal();
        boolean hasNext = pageParam.hasNext();
        boolean hasPrevious = pageParam.hasPrevious();

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("items", records);
        map.put("current", current);
        map.put("pages", pages);
        map.put("size", size);
        map.put("total", total);
        map.put("hasNext", hasNext);
        map.put("hasPrevious", hasPrevious);

        return map;
    }

    /**
     * 前台查询课程详情
     *
     * @param courseId 课程id
     * @return
     */
    @Override
    public CourseFrontInfoVo selectInfoWebById(String courseId) {
        this.updatePageViewCount(courseId);

        return baseMapper.selectInfoWebById(courseId);
    }

    /**
     * 更新浏览量
     *
     * @param id 课程id
     */
    @Override
    public void updatePageViewCount(String id) {
        EduCourse course = baseMapper.selectById(id);
        course.setViewCount(course.getViewCount() + 1);
        baseMapper.updateById(course);
    }

    /**
     * @Description: 查询上周和本周课程发布情况
     * @date 2022-04-04 18:04:51
     * @return:
     */
    @Override
    public Map<String, Object> countLastAndCurrentWeekCourse() {
        List<DayDataVo> dayDataVos1 = baseMapper.countLastWeekCourse();
        List<DayDataVo> dayDataVos2 = baseMapper.countCurrentWeekCourse();
        List<Integer> LastDays = new ArrayList<>();
        List<Integer> lastCourses = new ArrayList<>();
        List<Integer> currentDays = new ArrayList<>();
        List<Integer> currentCourses = new ArrayList<>();
        WeekDataVo lastWeekData = new WeekDataVo();
        WeekDataVo currentWeekData = new WeekDataVo();
        for (DayDataVo dayDataVo : dayDataVos1) {
            LastDays.add(dayDataVo.getDay());
            lastCourses.add(dayDataVo.getCourse());
        }
        lastWeekData.setDays(LastDays);
        lastWeekData.setDatas(lastCourses);
        for (DayDataVo dayDataVo : dayDataVos2) {
            currentDays.add(dayDataVo.getDay());
            currentCourses.add(dayDataVo.getCourse());
        }
        currentWeekData.setDays(currentDays);
        currentWeekData.setDatas(currentCourses);

        Map<String, Object> map = new HashMap<>();
        map.put("lastWeekData", lastWeekData);
        map.put("currentWeekData", currentWeekData);
        return map;
    }

}
